package com.jzsk.variable.center.zhengxin.base.exception;

import com.jzsk.variable.center.common.base.ServiceException;
import com.jzsk.variable.center.domain.enums.StatusCodeEnum;
import com.jzsk.variable.center.domain.vo.ResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.List;

/**
 * @author jiangli
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseVO<Object> exceptionHandler(Exception e) {
        log.error(e.getMessage(), e);
        return ResponseVO.error(StatusCodeEnum.系统繁忙);
    }

    @ExceptionHandler(ServiceException.class)
    @ResponseBody
    public ResponseVO<Object> serviceExceptionHandler(Exception e) {
        ServiceException serviceException = (ServiceException) e;
        Integer code = serviceException.getCode();
        String message = serviceException.getMessage();

        log.error(String.format("code：%s，message：%s", code, message), serviceException);
        //前端需要知道状态码的
        List<Integer> codes = Arrays.asList(2, 10);
        if (codes.contains(code) || code >= 70) {
            return ResponseVO.error(code, message);
        }
        return ResponseVO.error(StatusCodeEnum.系统繁忙);
    }

    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseVO<Object> methodArgumentNotValidHandler(Exception e) {
        MethodArgumentNotValidException exception = (MethodArgumentNotValidException) e;
        List<FieldError> allErrors = exception.getBindingResult().getFieldErrors();
        FieldError objectError = allErrors.get(0);
        return ResponseVO.error(StatusCodeEnum.请求参数异常.getCode(), StatusCodeEnum.请求参数异常.getMessage() +
                " " + objectError.getField() + " " + objectError.getDefaultMessage());
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseBody
    public ResponseVO<Object> missingParameterExceptionHandler(Exception e) {
        MissingServletRequestParameterException exception = (MissingServletRequestParameterException) e;
        log.error(String.format("缺少参数：%s，参数类型：%s", exception.getParameterName(),
                exception.getParameterType()), exception);
        return ResponseVO.error(StatusCodeEnum.系统繁忙.getCode(), String.format("缺少参数：%s，参数类型：%s",
                exception.getParameterName(), exception.getParameterType()));
    }

}